package com.crimsec.utils.dinfo.impl;

import com.crimsec.utils.dinfo.IRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.SortedMap;

public class SimpleRenderer extends AbstractRenderer implements IRenderer {

    private static ResourceBundle msgs = ResourceBundle.getBundle("i18n.Msg");

    public void render(SortedMap<Long, File> files, File initial, String name, int count)
            throws IOException {

        check(files, initial, name);

        PrintWriter pw = new PrintWriter(new FileOutputStream(new File(initial, name)));
        try {
            printHeader(pw);
            printFiles(pw, files, count);
            printFooter(pw);
        } finally {
            pw.close();
        }
    }

    private void printHeader(PrintWriter pw) throws IOException {
        String msg = msgs.getString("header-greeting");
        pw.write(msg + "\n\n");

    }

    private void printFiles(PrintWriter pw, SortedMap<Long, File> files, int count)
            throws IOException {
        SortedMap<Long, File> psm = getHeadMapForCount(files, count);

        Object[] i18n_msgs_args = new Object[2];
        MessageFormat mf = new MessageFormat(msgs.getString("file-msg"));//шаблон сообщения в ресурсах
        
        for (File f : psm.values()) {
            i18n_msgs_args[0] = f.getName();
            i18n_msgs_args[1] = new Date(f.lastModified()); 
            pw.write(mf.format(i18n_msgs_args));
            // pw.write(mf.format(new Object[]{f.getName(), new Date(f.lastModified())}));//может вызвать performance degradation
        }

    }

    private void printFooter(PrintWriter pw) throws IOException {
        pw.write("\n");
        String msg = msgs.getString("header-greeting");
        pw.write("пока все\n");
    }
}
